import axios from 'axios';
// import { from } from 'core-js/core/array';
import { Message } from 'element-ui';
import router from '../router';
axios.defaults.timeout = 40000;

import Vue from 'vue'

axios.defaults.baseURL = process.env.API_ROOT
axios.interceptors.request.use(config => {
    config.headers['Authorization'] = `Bearer ${Vue.prototype.$keycloak.token}`;
    return config;
}, error => {
    return Promise.reject(error)
})


// 响应拦截
axios.interceptors.response.use(response => {
    return response.data;
}, error => {
    const { status } = error.response;
    console.log(error.response)
    //TODO 需要改一下判断方式 
    if (status == 401) {
        // try {
        //     if (error.response.request.responseURL.indexOf('/oauth/token') > -1) {
        //         return Promise.reject(error)
        //     }
        // } catch (error) {
            
        // }
        Message.error("token失效,请重新登录");
        window.localStorage.clear()
        window.sessionStorage.clear()
        //清除token
        // localStorage.removeItem('eleToken');
        //重新登录
        // router.push('/')
    }

    return Promise.reject(error)
})


export function getLogin(url) {
    return new Promise((resolve, reject) => {
        axios.post(url, '', {
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
            }
        }).then(response => {
            resolve(response.data);
        }).catch(error => {
            reject(error.response.data)
        })
    })
}



/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function get(url, params = {}) {
     return   axios.get(url, {
            params: params
        }) 
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url, data = {}) {
    delete data.page;
    delete data.size;
    delete data.field;
    delete data.order;
    return   axios.post(url, data);

}


/**
 * 封装DELETE请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function Delete(url, data = {}) {
     
       return  axios.delete(url, data);
            
}


export function exportXlsx(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data,{responseType: 'blob'})
            .then(res => {
                console.log(res)
                resolve(res);
            }, err => {
                reject(err)
            })
    })
}